#include<iostream>
#include<vector>
using namespace std;


class Solution {
public:
    int numSubmat(vector<vector<int>>& mat) {
        int n = mat.size();
        int m = mat[0].size();
        vector<vector<int>> tmpArr(n + 1, vector<int>(m + 1, 0));
        for (int i = 1; i < n + 1; i++) {
            for (int j = 1; j < m + 1; j++) {
                tmpArr[i][j] = tmpArr[i][j - 1] + mat[i - 1][j - 1];
            }
        }
        for (int i = 1; i < n + 1; i++) {
            for (int j = 1; j < m + 1; j++) {
                tmpArr[i][j] += tmpArr[i - 1][j];
            }
        }
        int maxH = n;
        int maxL = m;
        int ans = 0;
        for (int H = 1; H <= maxH; H++)
            for (int L = 1; L <= maxL; L++) {
                for (int i = H; i <= n; i++) {
                    for (int j = L; j <= m; j++) {
                        if (L * H == tmpArr[i][j] + tmpArr[i - H][j - L] -
                            tmpArr[i - H][j] - tmpArr[i][j - L]) {
                            ans++;
                        }
                    }
                }
            }
        return ans;
    }
};